<template>
  <div class="dept-select">
    <van-field
      clickable
      readonly
      :is-link="!readonly"
      :label="label"
      :value="selectValue"
      :placeholder="placeholder"
      :required="required"
      :disabled="disabled"
      @click="showSelectDlg = !readonly"
    />
    <van-popup
      v-model="showSelectDlg"
      position="bottom"
      get-container="body"
      :overlay="false"
      style="height: 100vh; width: 100vw; background: #F6F6F6;"
    >
      <DeptSelectDlg
        :rowKey="props.value"
        :value="value"
        :multiple="multiple"
        @input="onSelectChange"
        @close="onCloseSelectDlg"
      />
    </van-popup>
  </div>
</template>

<script>
import DeptSelectDlg from './deptSelectDlg.vue';
import { SysCommonBizController } from '@/api';

export default {
  name: 'deptSelect',
  props: {
    label: {
      type: String,
      default: '部门选择'
    },
    value: {
      type: [String, Number, Array]
    },
    props: {
      type: Object,
      default: () => {
        return {
          label: 'deptName',
          value: 'deptId'
        }
      }
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String
    }
  },
  components: {
    DeptSelectDlg
  },
  data () {
    return {
      showSelectDlg: false,
      selectedItems: []
    }
  },
  methods: {
    onCloseSelectDlg () {
      this.showSelectDlg = false;
    },
    onSelectChange (val) {
      let temp = this.multiple ? val : val[0];
      this.$emit('input', temp);
      this.$emit('change', temp);
    },
    getSelectDeptList () {
      let params = {
        widgetType: 'upms_dept'
      };
      if (this.value == null || this.value.length <= 0) this.selectedItems = [];
      if (this.multiple) {
        params.fieldValues = Array.isArray(this.value) ? this.value : []
      } else {
        params.fieldValues = Array.isArray(this.value) ? this.value[0] : this.value;
        params.fieldValues = params.fieldValues == null ? [] : [params.fieldValues];
      }
      if (Array.isArray(params.fieldValues) && params.fieldValues.length > 0) {
        params.fieldValues = params.fieldValues.join(',');
        SysCommonBizController.viewByIds(this, params).then(res => {
          if (Array.isArray(res.data)) this.selectedItems = res.data;
        }).catch(e => {});
      }
    }
  },
  computed: {
    selectValue () {
      let labelList = (this.selectedItems || []).map(item => item[this.props.label]);
      return labelList.length > 0 ? labelList.join(', ') : undefined;
    }
  },
  watch: {
    value: {
      handler () {
        this.getSelectDeptList();
      },
      immediate: true
    }
  }
}
</script>

<style>
</style>
